﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;

namespace LevenBlog.Data.SqlServer
{
    public sealed class SqlLog : ILog
    {
        public int Count(IDbProvider provider)
        {
            string sql = "select count([id]) from [lb_log]";
            return Convert.ToInt32(SqlHelper.Instance.ExecuteScalar(provider, sql));
        }

        public void Insert(IDbProvider provider, lb_log log)
        {
            IDataParameter[] paras = null;
            string sql = SqlHelper.Instance.CreateInsertSql(log, out paras);
            SqlHelper.Instance.ExecuteNonQuery(provider, sql, paras);
        }

        public void Update(IDbProvider provider, lb_log log)
        {
            IDataParameter[] paras = null;
            string sql = SqlHelper.Instance.CreateUpdateSql(log, out paras);
            SqlHelper.Instance.ExecuteNonQuery(provider, sql, paras);
        }

        public void Delete(IDbProvider provider, int id)
        {
            string sql = string.Format("delete from [lb_log] where [id]={0}", id);
            SqlHelper.Instance.ExecuteNonQuery(provider, sql);
        }

        public void DeleteFromDateTime(IDbProvider provider, DateTime startTime, DateTime endTime)
        {
            string sql = string.Format("delete from [lb_log] where [time] between '{0}' and '{1}'", startTime, endTime);
            SqlHelper.Instance.ExecuteNonQuery(provider, sql);
        }

        public void DeleteFromDateTime(IDbProvider provider, DateTime endTime)
        {
            string sql = string.Format("delete from [lb_log] where [time] < '{0}'", endTime);
            SqlHelper.Instance.ExecuteNonQuery(provider, sql);
        }

        public lb_log Get(IDbProvider provider, int id)
        {
            string sql = string.Format("select * from [lb_log] where [id]={0}", id);
            using (IDataReader dr = SqlHelper.Instance.ExecuteDataReader(provider, sql))
            {
                return SqlHelper.Instance.ConvertToEntity<lb_log>(dr);
            }
        }

        public IList<lb_log> Get(IDbProvider provider, int pageSize, int currentPage)
        {
            if (currentPage < 1)
                currentPage = 1;
            string sql = PageHelper.BuildPageSql(pageSize, currentPage, "*", "[lb_log]", string.Empty, "[id]", "order by [id] desc");
            using (IDataReader dr = SqlHelper.Instance.ExecuteDataReader(provider, sql))
            {
                return SqlHelper.Instance.ConvertToList<lb_log>(dr);
            }
        }
    }
}
